package com.erpanderp.wam.usm.model.service.user;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.hibernate.FlushMode;
import org.hibernate.Query;
import org.hibernate.Session;

import com.erpanderp.wam.adm.model.entity.SAPERPModule;
import com.erpanderp.wam.tm.model.entity.RecruitmentRequest;
import com.erpanderp.wam.usm.model.entity.leave.LeaveBalance;
import com.erpanderp.wam.usm.model.entity.projectandassignment.Project;
import com.erpanderp.wam.usm.model.entity.user.Employee;
import com.erpanderp.wam.util.CommonLookup;
import com.erpanderp.wam.util.HibernateUtil;
import com.itextpdf.text.log.SysoLogger;

public class EmployeeDAO {

	public String generateEmployeeCode() {
		String maxCode = null;
		String newCode = null;

		try {
			Session session = HibernateUtil.getSessionFactory()
					.getCurrentSession();
			session.beginTransaction();
			String queryString = "select max(e.employeeCode) from Employee e";

			Query query = session.createQuery(queryString);
			query.setCacheable(false);
			maxCode = (String) query.uniqueResult();

			if (maxCode == null) {
				newCode = CommonLookup.EMPLOYEE_CODE_START;
			} else {
				maxCode = maxCode.substring(1);
				newCode = CommonLookup.EMPLOYEE_CODE_START_CHARACTER
						+ String.valueOf(Integer.parseInt(maxCode) + 1);
			}

			session.close();
			return newCode;

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public List<Employee> getAllHrs() {
		List<Employee> allhrs = null;
		String hrRole = CommonLookup.STANDARD_ROLE_HR;

		try {
			Session session = HibernateUtil.getSessionFactory()
					.getCurrentSession();
			session.beginTransaction();
			session.setFlushMode(FlushMode.COMMIT);
			Query query = session
					.createQuery(
							"select e.employee from EmployeeRole e where e.role.role=:hrRole")
					.setString("hrRole", hrRole);
			query.setCacheable(false);
			allhrs = (List<Employee>) query.list();
			session.getTransaction().commit();

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return allhrs;
	}

	public Employee registerEmployee(Employee employee) {
		try {
			Session session = HibernateUtil.getSessionFactory()
					.getCurrentSession();
			session.beginTransaction();
			session.setFlushMode(FlushMode.AUTO);
			session.save(employee);
			session.getTransaction().commit();
			return employee;

		} catch (Exception e) {
			e.printStackTrace();
			return null;

		}

	}

	public List<LeaveBalance> assignLeaveBalance(
			List<LeaveBalance> leaveBalances) {
		System.out.println("LEAVEBALANCES SIZE IS:" + leaveBalances.size());
		System.out.println("LEAVES ASSIGNING IN PROGRESS");

		try {
			Session session = HibernateUtil.getSessionFactory()
					.getCurrentSession();
			session.beginTransaction();
			session.setFlushMode(FlushMode.AUTO);
			for (LeaveBalance leaveBalance : leaveBalances) {
				session.saveOrUpdate(leaveBalance);
			}
			session.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return leaveBalances;

	}

	public List<Employee> getProjectManagers() {
		List<Employee> projectMangersList = null;
		String chRole = CommonLookup.STANDARD_ROLE_CH;
		String vpRole = CommonLookup.STANDARD_ROLE_VP;
		String pmRole = CommonLookup.STANDARD_ROLE_PROJECT_MANAGER;
		String cmdRole = CommonLookup.STANDARD_ROLE_CMD;
		String cooRole = CommonLookup.STANDARD_ROLE_COO;
		try {
			Session session = HibernateUtil.getSessionFactory()
					.getCurrentSession();
			session.beginTransaction();
			session.setFlushMode(FlushMode.COMMIT);
			String queryString = "select er.employee from EmployeeRole er where er.role.role in(:chRole,:vpRole,:pmRole,:cmdRole,:cooRole)";
			Query query = session.createQuery(queryString)
					.setString("chRole", chRole).setString("vpRole", vpRole)
					.setString("pmRole", pmRole).setString("cmdRole", cmdRole)
					.setString("cooRole", cooRole);
			query.setCacheable(false);
			projectMangersList = query.list();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return projectMangersList;

	}

	public List<Employee> getAllCompetencyLeadsAndProjectManagers() {
		List<Employee> projectMangersList = null;
		String chRole = CommonLookup.STANDARD_ROLE_CH;
		String vpRole = CommonLookup.STANDARD_ROLE_VP;
		String pmRole = CommonLookup.STANDARD_ROLE_PROJECT_MANAGER;
		String cmdRole = CommonLookup.STANDARD_ROLE_CMD;
		try {
			Session session = HibernateUtil.getSessionFactory()
					.getCurrentSession();
			session.beginTransaction();
			session.setFlushMode(FlushMode.COMMIT);
			String queryString = "select er.employee from EmployeeRole er where er.role.role in(:chRole,:vpRole,:pmRole,:cmdRole)";
			Query query = session.createQuery(queryString)
					.setString("chRole", chRole).setString("vpRole", vpRole)
					.setString("pmRole", pmRole).setString("cmdRole", cmdRole);
			query.setCacheable(false);
			projectMangersList = query.list();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return projectMangersList;

	}

	public List<String> getAllEmployeeEmialIds() {
		List<String> employeeEmailIds = new ArrayList<String>();
		try {
			System.out.println("............email...........");
			Session session = HibernateUtil.getSessionFactory()
					.getCurrentSession();
			session.beginTransaction();
			session.setFlushMode(FlushMode.COMMIT);
			String queryString = "select e.email from Employee e";
			System.out
					.println("............select e.email from Employee e...........");
			Query query = session.createQuery(queryString);
			query.setCacheable(false);
			employeeEmailIds = (List<String>) query.list();
			System.out
					.println("............select e.email from Employee e..........."
							+ employeeEmailIds.size());
			session.getTransaction().commit();
			return employeeEmailIds;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public Employee getEmployeeByEmployeeId(Long employeeId) {
		Employee employee = null;
		try {
			Session session = HibernateUtil.getSessionFactory()
					.getCurrentSession();
			session.beginTransaction();
			session.setFlushMode(FlushMode.COMMIT);
			String queryString = "from Employee e where e.employeeId=:employeeId";
			Query query = session.createQuery(queryString).setLong(
					"employeeId", employeeId);
			employee = (Employee) query.uniqueResult();
			session.getTransaction().commit();
			return employee;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public Employee getEmployeeByEmployeeCode(String employeeCode) {
		Employee employee = new Employee();
		try {
			Session session = HibernateUtil.getSessionFactory()
					.getCurrentSession();
			session.beginTransaction();
			session.setFlushMode(FlushMode.AUTO);
			String queryString = "from Employee e where e.employeeCode = :employeeCode";
			Query query = session.createQuery(queryString).setString(
					"employeeCode", employeeCode);
			query.setCacheable(false);
			employee = (Employee) query.uniqueResult();
			session.getTransaction().commit();
			return employee;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public Employee getVP() {
		Employee employee = new Employee();
		try {
			Session session = HibernateUtil.getSessionFactory()
					.getCurrentSession();
			session.beginTransaction();
			session.setFlushMode(FlushMode.AUTO);
			String queryString = "select er.employee from EmployeeRole er where er.role.role = 'VP'";
			Query query = session.createQuery(queryString);
			query.setCacheable(false);
			employee = (Employee) query.uniqueResult();
			session.getTransaction().commit();
			return employee;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public List<Employee> getCompetencyLeads() {
		List<Employee> competencyLeadsList = null;

		String chRole = CommonLookup.STANDARD_ROLE_CH;
		String vpRole = CommonLookup.STANDARD_ROLE_VP;
		String clRole = CommonLookup.STANDARD_ROLE_COMPETENCY_LEAD;
		String pmRole = CommonLookup.STANDARD_ROLE_PROJECT_MANAGER;
		String cmdRole = CommonLookup.STANDARD_ROLE_CMD;
		String cooRole = CommonLookup.STANDARD_ROLE_COO;
		try {
			Session session = HibernateUtil.getSessionFactory()
					.getCurrentSession();
			session.beginTransaction();
			session.setFlushMode(FlushMode.COMMIT);
			String queryString = "select er.employee from EmployeeRole er where er.role.role in(:chRole,:vpRole,:clRole,:cmdRole,:pmRole,:cooRole)";
			Query query = session.createQuery(queryString)
					.setString("chRole", chRole).setString("vpRole", vpRole)
					.setString("clRole", clRole).setString("pmRole", pmRole)
					.setString("cmdRole", cmdRole)
					.setString("cooRole", cooRole);
			query.setCacheable(false);
			competencyLeadsList = query.list();
			System.out.println("SIZE: " + competencyLeadsList.size());
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return competencyLeadsList;

	}

	public List<Employee> getCenterHeads() {
		List<Employee> centerHeads = new ArrayList<Employee>();
		String chRole = CommonLookup.STANDARD_ROLE_CH;
		try {
			Session session = HibernateUtil.getSessionFactory()
					.getCurrentSession();
			session.beginTransaction();
			session.setFlushMode(FlushMode.COMMIT);
			String queryString = "select er.employee from EmployeeRole er where er.role.role=:chRole";

			Query query = session.createQuery(queryString).setString("chRole",
					chRole);
			query.setCacheable(false);
			centerHeads = (List<Employee>) query.list();
			System.out.println("----->CENTERHEADS ARE" + (centerHeads == null));
			session.getTransaction().commit();

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return centerHeads;
	}

	public List<Employee> getAllEmployees() {
		List<Employee> employees = new ArrayList<Employee>();
		try {
			Session session = HibernateUtil.getSessionFactory()
					.getCurrentSession();
			session.beginTransaction();
			session.setFlushMode(FlushMode.COMMIT);
			String queryString = "from Employee e where e.status = :employeeStatus order by e.employeeCode asc";
			Query query = session.createQuery(queryString).setString(
					"employeeStatus", CommonLookup.STATUS_ACTIVE);
			query.setCacheable(false);
			employees = (List<Employee>) query.list();
			session.close();
			return employees;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}

	public List<Employee> getEmployees(String name) {
		name = "'%" + name + "%'";
		name = name.replaceAll(" ", "%','%");
		name = name.replaceAll("%20", "%','%");
		
		String names[] = name.split(",");

		String superVisorName = name;
		try {
			Session session = HibernateUtil.getSessionFactory()
					.getCurrentSession();
			session.setFlushMode(FlushMode.AUTO);
			session.beginTransaction();
			String queryString = "from Employee e where (e.firstName like "
					+ names[0];
			for (int i = 1; i < names.length; i++) {
				queryString += " or e.firstName like " + names[i];
			}
			queryString += ") or (e.lastName like " + names[0];
			for (int i = 1; i < names.length; i++) {
				queryString += " or e.lastName like " + names[i];
			}
			queryString += ")";

			System.out.println(queryString);
			List<Employee> tempList = (List<Employee>) session
					.createQuery(queryString).setCacheable(false).list();
			session.getTransaction().commit();
			return tempList;
		} catch (Exception e) {
			e.printStackTrace();

			return null;
		}

	}

	public List<Employee> getEmployees(String moduleName, String location,
			String employeeCode, String employeeName) {
		List<Employee> employees = new ArrayList<Employee>();
		try {
			Session session = HibernateUtil.getSessionFactory()
					.getCurrentSession();
			session.beginTransaction();
			session.setFlushMode(FlushMode.COMMIT);
			String queryString = "from Employee e where e.status = :status";

			if (moduleName != null && !moduleName.equals("")) {
				queryString += " and e.moduleName = :moduleName";
			}

			if (location != null && !location.equals("")) {
				queryString += " and e.location = :location";
			}

			if (employeeCode != null && !employeeCode.equals("")) {
				queryString += " and e.employeeCode = :employeeCode";
			}

			if (employeeName != null && !employeeName.equals("")) {
				queryString += " and (e.firstName = :employeeName or e.lastName = :employeeName)";
			}

			Query query = session.createQuery(queryString);
			query.setCacheable(false).setString("status",
					CommonLookup.STATUS_ACTIVE);

			if (moduleName != null && !moduleName.equals("")) {
				query.setString("moduleName", moduleName);
			}

			if (location != null && !location.equals("")) {
				query.setString("location", location);
			}

			if (employeeCode != null && !employeeCode.equals("")) {
				query.setString("employeeCode", employeeCode);
			}

			if (employeeName != null && !employeeName.equals("")) {
				query.setString("employeeName", employeeName);
			}

			employees = (List<Employee>) query.list();
			session.getTransaction().commit();
			return employees;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public Employee updateEmployee(Employee employee) {
		try {
			Session session = HibernateUtil.getSessionFactory()
					.getCurrentSession();
			session.beginTransaction();
			session.setFlushMode(FlushMode.COMMIT);
			session.saveOrUpdate(employee);
			session.getTransaction().commit();
			return employee;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public boolean isNewJoinee(Employee employee) {
		System.out.println("CHECKING NEW JOINEE OR NOT");
		return false;

	}

	public static void main(String a[]) {
		System.out.println(new EmployeeDAO().getVP());
		System.out.println(new EmployeeDAO().getEmployees("tho"));
	}

	public List<Employee> getAllModules() {
		List<Employee> allModules = null;
		try {
			Session session = HibernateUtil.getSessionFactory()
					.getCurrentSession();
			session.beginTransaction();
			session.setFlushMode(FlushMode.COMMIT);
			Query query = session.createQuery("from Employee e");
			query.setCacheable(false);
			allModules = (List<Employee>) query.list();
			session.getTransaction().commit();

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return allModules;
	}

	public List<Employee> getEmployeeByModuleName(String moduleName) {
		List<Employee> allEmployees = null;
		System.out.println("Employees method..........");
		String active = CommonLookup.STATUS_ACTIVE;
		try {
			Session session = HibernateUtil.getSessionFactory()
					.getCurrentSession();
			session.beginTransaction();
			session.setFlushMode(FlushMode.AUTO);
			String queryString = "from Employee e where e.moduleName = :moduleName and e.status=:active";
			Query query = session.createQuery(queryString)
					.setString("moduleName", moduleName)
					.setString("active", active);
			query.setCacheable(false);
			allEmployees = (List<Employee>) query.list();
			session.getTransaction().commit();

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return allEmployees;
	}

	public List<Employee> getAllEmployeesByCurrentDate() {

		List<Employee> employees = new ArrayList<Employee>();
		Calendar calendar = Calendar.getInstance();
		int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
		int month = calendar.get(Calendar.MONTH) + 1;
		try {
			Session session = HibernateUtil.getSessionFactory()
					.getCurrentSession();
			session.beginTransaction();
			session.setFlushMode(FlushMode.COMMIT);
			String queryString = "from Employee e where MONTH(e.dateOfBirth)=:month and DAY(e.dateOfBirth)=:dayOfMonth";
			Query query = session.createQuery(queryString)
					.setInteger("dayOfMonth", dayOfMonth)
					.setInteger("month", month);
			query.setCacheable(false);
			employees = (List<Employee>) query.list();
			session.getTransaction().commit();
			return employees;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	
}
